<template>
    <div class="app-container">
        <el-row :gutter="20">
            <!--部门数据-->
            <el-col :span="4" :xs="24">
                <div class="head-container">
                    <el-input
                        v-model="deptName"
                        placeholder=""
                        clearable
                        size="small"
                        prefix-icon="el-icon-search"
                        style="margin-bottom: 20px"
                    />
                    <el-button @click="scaleTree" type="text">{{
                        boolExpand ? "全部收起" : "全部展开"
                    }}</el-button>
                </div>

                <div class="head-container">
                    <el-tree
                        :data="deptOptions"
                        :props="defaultProps"
                        :expand-on-click-node="false"
                        :filter-node-method="filterNode"
                        ref="tree"
                        default-expand-all
                        highlight-current
                        node-key="id"
                        @node-click="handleNodeClick"
                    />
                </div>
            </el-col>
            <!--用户数据-->
            <el-col :span="20" :xs="24">
                <TableCard>
                    <el-row :gutter="10" class="mb8">
                        <el-col :span="1.5">
                            <el-button
                                type="primary"
                                plain
                                icon="el-icon-plus"
                                size="mini"
                                @click="handleAdd"
                                v-hasPermi="['system:user:add']"
                                >添加部门</el-button
                            >
                        </el-col>
                    </el-row>

                    <el-table
                        :border="Global.tableShowBorder"
                        v-loading="loading"
                        :data="userList"
                        @selection-change="handleSelectionChange"
                    >
                        <el-table-column
                            type="index"
                            label="序号"
                        ></el-table-column>
                        <el-table-column
                            prop="deptName"
                            label="部门名称"
                            width="260"
                        >
                            <template slot-scope="scope">
                                <span
                                    v-if="
                                        $store.getters.allDefectObj[
                                            'HR-WEB-022'
                                        ] == 0
                                    "
                                    @click="handleDetail(scope.row)"
                                >
                                    {{ scope.row.deptName }}</span
                                >
                                <span
                                    v-else
                                    @click="handleDetail(scope.row)"
                                    style="
                                        color: #2d93fc;
                                        cursor: pointer;
                                        text-decoration: underline;
                                    "
                                    >{{ scope.row.deptName }}</span
                                >
                            </template>
                        </el-table-column>

                        <!-- <el-table-column
                            prop="orderNum"
                            label="排序"
                            width="120"
                        ></el-table-column> -->
                        <el-table-column
                            prop="leader"
                            label="部门负责人"
                            width="120"
                        >
                            <template slot-scope="scope">
                                <span>{{ scope.row.leader }}</span>
                                <span
                                    v-if="scope.row.staffType == 3"
                                    style="color: red"
                                    >(异)</span
                                >
                            </template>
                        </el-table-column>

                        <!-- <el-table-column prop="status" label="状态" width="100">
                    <template slot-scope="scope">
                        <dict-tag
                            :options="dict.type.sys_normal_disable"
                            :value="scope.row.status"
                        />
                    </template>
                </el-table-column> -->
                        <!-- <el-table-column
                    label="创建时间"
                    align="center"
                    prop="createTime"
                    width="200"
                >
                    <template slot-scope="scope">
                        <span>{{ parseTime(scope.row.createTime) }}</span>
                    </template>
                </el-table-column> -->
                        <el-table-column
                            label="操作"
                            align="center"
                            class-name="small-padding fixed-width"
                        >
                            <template slot-scope="scope">
                                <el-button
                                    size="mini"
                                    type="text"
                                    icon="el-icon-edit"
                                    @click="handleUpdate(scope.row)"
                                    v-hasPermi="['system:dept:edit']"
                                    >修改
                                </el-button>
                                <!-- <el-button
                                    size="mini"
                                    type="text"
                                    icon="el-icon-plus"
                                    @click="handleAdd(scope.row)"
                                    v-hasPermi="['system:dept:add']"
                                    >新增
                                </el-button> -->
                                <el-button
                                    v-if="scope.row.parentId != 0"
                                    size="mini"
                                    type="text"
                                    icon="el-icon-delete"
                                    @click="handleDelete(scope.row)"
                                    v-hasPermi="['system:dept:remove']"
                                    >删除
                                </el-button>
                                <el-button
                                    size="mini"
                                    type="text"
                                    icon="el-icon-s-custom"
                                    @click="chargeLeader(scope.row)"
                                    v-hasPermi="['system:dept:zdfzr']"
                                    >指定负责人
                                </el-button>
                                <el-button
                                    size="mini"
                                    type="text"
                                    icon="el-icon-delete"
                                    @click="deleteLeader(scope.row)"
                                    v-hasPermi="['system:dept:scfzr']"
                                    >删除负责人
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>

                    <!-- <pagination
                        v-show="total > 1000"
                        :total="total"
                        :page.sync="queryParams.pageNum"
                        :limit.sync="queryParams.pageSize"
                        @pagination="getList"
                    /> -->
                </TableCard>
            </el-col>
        </el-row>

        <!-- 添加或修改用户配置对话框 -->
        <el-dialog
            :title="title"
            :visible.sync="open"
            width="520px"
            append-to-body
        >
            <el-form
                ref="form"
                :model="form"
                :rules="readOnly ? '' : rules"
                label-width="120px"
            >
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="所属部门" prop="parentId">
                            <treeselect
                                disabled
                                v-model="form.parentId"
                                :options="deptOptions"
                                :show-count="true"
                                placeholder=""
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="部门名称" prop="deptName">
                            <el-input
                                :disabled="readOnly"
                                v-model="form.deptName"
                                placeholder=""
                                clearable
                            />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="24">
                        <el-form-item label="岗位职责" prop="remark">
                            <el-input
                                :disabled="readOnly"
                                v-model="form.remark"
                                clearable
                                type="textarea"
                                :rows="5"
                                placeholder=""
                            ></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="显示顺序" prop="orderNum">
                            <el-input-number
                                :disabled="readOnly"
                                v-model="form.orderNum"
                                controls-position="right"
                                :min="1"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" v-if="!readOnly" @click="submitForm"
                    >保 存</el-button
                >
                <el-button @click="cancel">{{
                    readOnly ? "关 闭" : "取 消"
                }}</el-button>
            </div>
        </el-dialog>

        <!-- 重置密码对话框 -->
        <el-dialog
            :title="rpTitle"
            :visible.sync="rpVision"
            width="350px"
            append-to-body
        >
            <el-form
                ref="rpForm"
                :model="rpForm"
                :rules="rpRules"
                label-width="120px"
            >
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="部门名称" prop="deptName">
                            <span>{{ rpForm.deptName }}</span>
                        </el-form-item></el-col
                    >
                    <el-col :span="24">
                        <el-form-item label="负责人" prop="leader">
                            <el-input
                                suffix-icon="el-icon-search"
                                readonly
                                @focus="showTableDialog"
                                v-model="rpForm.leader"
                                placeholder=""
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="rsSubmit">确 定</el-button>
                <el-button @click="rsCancel">关 闭</el-button>
            </div>
        </el-dialog>
        <userTableDialog
            title="选择负责人"
            :defaultParams="defaultParams"
            :open.sync="showTableVision"
            @confirm="setFormBase"
        >
        </userTableDialog>
    </div>
</template>

<script>
import {
    listDept,
    getDept,
    delDept,
    addDept,
    updateDept,
    listDeptExcludeChild,
} from "@/api/system/dept";

import {
    listUser,
    getUser,
    delUser,
    addUser,
    updateUser,
    resetUserPwd,
    changeUserStatus,
} from "@/api/system/user";

import { treeselect, getDeptByParentId } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

import { getToken } from "@/utils/auth";

import { listPostAll } from "@/api/system/post";

export default {
    name: "User",
    dicts: ["sys_normal_disable", "sys_user_sex"],
    components: { Treeselect },
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示查询条件
            showSearch: true,
            // 总条数
            total: 0,
            // 用户表格数据
            userList: null,
            // 弹出层标题
            title: "",
            // 部门树选项
            deptOptions: [],
            // 是否显示弹出层
            open: false,
            // 部门名称
            deptName: undefined,
            // 默认密码
            initPassword: undefined,
            // 日期范围
            dateRange: [],
            // 职位选项
            postOptions: [],
            // 角色选项
            roleOptions: [],
            // 表单参数
            form: {},
            defaultProps: {
                children: "children",
                label: "label",
            },
            // 用户导入参数
            upload: {
                // 是否显示弹出层（用户导入）
                open: false,
                // 弹出层标题（用户导入）
                title: "",
                // 是否禁用上传
                isUploading: false,
                // 是否更新已经存在的用户数据
                updateSupport: 0,
                // 设置上传的请求头部
                headers: { Authorization: "Bearer " + getToken() },
                // 上传的地址
                url: process.env.VUE_APP_BASE_API + "/system/user/importData",
            },
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 20,
                userName: undefined,
                phonenumber: undefined,
                status: undefined,
                deptId: undefined,
                staffNum: undefined,
            },
            // 列信息
            columns: [
                { key: 0, label: `用户编号`, visible: true },
                { key: 1, label: `姓名`, visible: true },
                { key: 2, label: `用户昵称`, visible: true },
                { key: 3, label: `部门`, visible: true },
                { key: 4, label: `手机号码`, visible: true },
                { key: 5, label: `状态`, visible: true },
                { key: 6, label: `创建时间`, visible: true },
            ],
            // 表单校验
            rules: {
                deptName: [
                    {
                        required: true,
                        message: "部门名称不能为空",
                        trigger: "blur",
                    },
                    {
                        max: 50,
                        message: "部门名称字符长度不超过50",
                        trigger: "blur",
                    },
                ],
                remark: [
                    {
                        max: 200,
                        message: "岗位职责字符长度不超过200",
                        trigger: "blur",
                    },
                ],
                orderNum: [
                    {
                        required: true,
                        message: "显示顺序不能为空",
                        trigger: "blur",
                    },
                ],
            },

            // 左侧树的展开与收起
            boolExpand: true, //默认全部展开
            //显示角色配置
            boolRole: false,
            rpTitle: "重置密码",
            //修改密码弹窗
            rpVision: false,
            rpForm: {},
            rpRules: {
                leader: [
                    {
                        required: true,
                        message: "负责人不能为空",
                        trigger: "change",
                    },
                ],
            },
            //角色弹窗
            roleVision: false,
            currentId: null,
            readOnly: false,

            showTableVision: false,
            // 过滤负责人
            defaultParams: {
                isLink: true,
                staffTypes:
                    this.$store.getters.allDefectObj["HR-WEB-027"] == 0
                        ? "1,4,5,6"
                        : "1,3,4,5,6",
            },
        };
    },
    watch: {
        // 根据名称筛选部门树
        deptName(val) {
            this.$refs.tree.filter(val);
        },
    },
    created() {
        // this.getList();
        this.getPostList();

        this.getTreeselect();
        this.getConfigKey("sys.user.initPassword").then((response) => {
            this.initPassword = response.msg;
        });
    },
    methods: {
        deleteLeader(row) {
            if (!row.leader) {
                this.$message({
                    type: "warning",
                    message: "该部门暂无负责人",
                });
                return;
            }
            if (this.$store.getters.allDefectObj["HR-WEB-028"] == 0) {
                getDept(row.deptId).then((response) => {
                    let tempObj = response.data;
                    tempObj.leader = "";
                    tempObj.staffNum = "";
                    updateDept(tempObj).then((response) => {
                        this.$message({
                            type: "success",
                            message: "删除成功",
                        });
                        this.getList();
                    });
                });
            } else {
                this.$modal
                    .confirm("确认要删除该部门负责人吗" + "？")
                    .then(() => {
                        getDept(row.deptId).then((response) => {
                            let tempObj = response.data;
                            tempObj.leader = "";
                            tempObj.staffNum = "";
                            updateDept(tempObj).then((response) => {
                                this.$message({
                                    type: "success",
                                    message: "删除成功",
                                });
                                this.getList();
                            });
                        });
                    });
            }
        },

        showTableDialog() {
            this.showTableVision = true;
        },
        //设置用户
        setFormBase(row) {
            this.rpForm.leader = row.realName;
            this.$set(this.rpForm, "staffNum", row.staffNum);
        },
        resetRp() {
            this.rpForm = {
                deptId: undefined,
                deptName: undefined,
                leader: undefined,
                staffNum: undefined,
            };
        },

        chargeLeader(row) {
            this.resetRp();

            getDept(row.deptId).then((response) => {
                this.rpForm = response.data;
                this.rpVision = true;
                this.rpTitle = "指定部门负责人";
            });
        },

        parsePostName(ids) {
            if (ids) {
                let nameArr = [];
                let selIds = ids.split(",");
                this.postList.forEach((item) => {
                    selIds.forEach((sel) => {
                        if (item.postId == sel) {
                            nameArr.push(item.postName);
                        }
                    });
                });
                return nameArr.join(",");
            }
            return "—";
        },
        getPostList() {
            listPostAll().then((res) => {
                this.postList = res.data;
            });
        },

        /** 查询用户列表 */
        getList() {
            this.loading = true;
            getDeptByParentId({ parentId: this.queryParams.deptId }).then(
                (response) => {
                    this.userList = response.data;
                    console.log(this.userList);
                    this.total = response.total;
                    this.loading = false;
                }
            );
        },

        // 值更新树不换选中的节点
        getTreeselect2() {
            treeselect().then((response) => {
                this.deptOptions = response.data;

                this.$nextTick(() => {
                    this.$refs.tree.setCurrentKey(this.queryParams.deptId);
                });
            });
        },
        /** 查询部门下拉树结构 */
        getTreeselect() {
            treeselect().then((response) => {
                this.deptOptions = response.data;
                // 在数据加载完成后，选中根节点
                if (response.data.length > 0) {
                    this.currentId = response.data[0].id;
                    this.$nextTick(() => {
                        this.$refs.tree.setCurrentKey(this.currentId);
                        this.queryParams.deptId = this.currentId;
                        this.getList();
                    });
                }
            });
        },
        // 筛选节点
        filterNode(value, data) {
            if (!value) return true;
            return data.label.indexOf(value) !== -1;
        },
        // 节点单击事件
        handleNodeClick(data) {
            this.queryParams.deptId = data.id;
            this.handleQuery();
        },
        // 用户状态修改
        handleStatusChange(row) {
            let text = row.status === "1" ? "启用" : "停用";
            this.$modal
                .confirm(
                    `${
                        row.status == 1
                            ? "确认要启用该用户吗？"
                            : "禁用用户后，用户将无法登录系统，确定要禁用该用户吗？"
                    }`
                )
                .then(function () {
                    return changeUserStatus(row.userId, String(row.status));
                })
                .then(() => {
                    this.$modal.msgSuccess(text + "成功");
                    this.getList();
                })
                .catch(function () {});
        },
        // 取消按钮
        cancel() {
            this.roleVision = false;
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {};
            this.resetForm("form");

            console.log("清楚后的表单", this.form);

            this.readOnly = false;
        },
        /** 查询按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dateRange = [];
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.userId);
            this.single = selection.length != 1;
            this.multiple = !selection.length;
        },
        // 更多操作触发
        handleCommand(command, row) {
            switch (command) {
                case "handleResetPwd":
                    this.handleResetPwd(row);
                    break;
                case "handleAuthRole":
                    this.handleAuthRole(row);
                    break;
                default:
                    break;
            }
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();

            this.form.parentId = this.queryParams.deptId;

            //todo 节点下有数据，自动设置为节点下长度+1
            if (this.$store.getters.allDefectObj["HR-WEB-023"] == 0) {
                this.form.orderNum = undefined;
            } else {
                this.form.orderNum = this.userList.length + 1 || 1;
            }

            this.open = true;

            this.title = "添加部门";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();

            const deptId = row.deptId || this.ids;
            getDept(deptId).then((response) => {
                this.form = response.data;
                this.open = true;
                this.title = "修改部门";
            });
        },

        /**查看详情 */
        handleDetail(row) {
            this.reset();
            // this.getTreeselect();
            const deptId = row.deptId || this.ids;
            getDept(deptId).then((response) => {
                this.form = response.data;
                this.readOnly = true;
                this.open = true;
                this.title = "查看部门";
            });
        },
        handleRole(row) {
            this.reset();
            this.boolRole = true;
            this.getTreeselect();
            const userId = row.userId || this.ids;
            getUser(userId).then((response) => {
                this.form = response.data;
                this.postOptions = response.posts;
                this.roleOptions = response.roles;
                this.form.postIds = response.postIds;
                this.form.roleIds =
                    response.roleIds && response.roleIds.length > 0
                        ? response.roleIds
                        : [110];

                this.roleVision = true;
                this.title = "角色配置";
                this.form.password = "";
            });
        },
        /** 重置密码按钮操作 */
        handleResetPwd(row) {
            this.$prompt('请输入"' + row.userName + '"的新密码', "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                closeOnClickModal: false,
                inputPattern: /^.{5,20}$/,
                inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
            })
                .then(({ value }) => {
                    resetUserPwd(row.userId, value).then((response) => {
                        this.$modal.msgSuccess("修改成功，新密码是：" + value);
                    });
                })
                .catch(() => {});
        },
        /** 分配角色操作 */
        handleAuthRole: function (row) {
            const userId = row.userId;
            this.$router.push("/system/user-auth/role/" + userId);
        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs["form"].validate((valid) => {
                if (valid) {
                    if (this.form.deptId != undefined) {
                        updateDept(this.form).then((response) => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getTreeselect2();
                            this.getList();
                        });
                    } else {
                        addDept(this.form).then((response) => {
                            this.$modal.msgSuccess("新增成功");
                            this.roleVision = false;
                            this.open = false;
                            this.getTreeselect2();
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        /** 删除按钮操作 */
        handleDelete(row) {
            this.$modal
                .confirm('是否确认删除名称为"' + row.deptName + '"的数据项？')
                .then(function () {
                    return delDept(row.deptId);
                })
                .then(() => {
                    this.getList();
                    this.getTreeselect();

                    this.$modal.msgSuccess("删除成功");
                })
                .catch((err) => {
                    if (err == "cancel") return;

                    this.$confirm(
                        "该部门下包含子部门或员工，不允许删除！",
                        "提示",
                        {
                            cancelButtonText: "关闭",
                            showConfirmButton: false,
                            type: "warning",
                        }
                    ).then(() => {
                        this.$message({
                            type: "success",
                            message: "删除成功!",
                        });
                        this.getTreeselect();
                        this.getList();
                    });
                });
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download(
                "system/user/export",
                {
                    ...this.queryParams,
                },
                `user_${new Date().getTime()}.xlsx`
            );
        },
        /** 导入按钮操作 */
        handleImport() {
            this.upload.title = "用户导入";
            this.upload.open = true;
        },
        /** 下载模板操作 */
        importTemplate() {
            this.download(
                "system/user/importTemplate",
                {},
                `user_template_${new Date().getTime()}.xlsx`
            );
        },
        // 文件上传中处理
        handleFileUploadProgress(event, file, fileList) {
            this.upload.isUploading = true;
        },
        // 文件上传成功处理
        handleFileSuccess(response, file, fileList) {
            this.upload.open = false;
            this.upload.isUploading = false;
            this.$refs.upload.clearFiles();
            this.$alert(
                "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
                    response.msg +
                    "</div>",
                "导入结果",
                { dangerouslyUseHTMLString: true }
            );
            this.getList();
        },
        // 提交上传文件
        submitFileForm() {
            this.$refs.upload.submit();
        },

        //左侧树的缩放
        scaleTree() {
            for (
                let i = 0;
                i < this.$refs.tree.store._getAllNodes().length;
                i++
            ) {
                // 遍历 el-tree 的每个节点，将节点的 expanded 属性设为 true 或 false
                this.$refs.tree.store._getAllNodes()[i].expanded =
                    !this.boolExpand;
            }
            this.boolExpand = !this.boolExpand;
        },
        // 指定负责人
        rsSubmit() {
            this.$refs["rpForm"].validate((valid) => {
                if (valid) {
                    updateDept(this.rpForm).then((response) => {
                        this.$modal.msgSuccess("指定负责人成功");
                        this.rpVision = false;
                        this.getTreeselect2();
                        this.getList();
                    });
                }
            });
        },
        rsCancel() {
            this.resetRp();
            this.rpVision = false;
        },
        changePassword(row) {
            this.resetRp();
            this.rpForm.nickName = row.nickName;
            this.rpForm.userId = row.userId;
            this.rpForm.userName = row.userName;

            this.rpVision = true;
        },
    },
};
</script>
